package com.wms.service.impl;

import com.wms.domain.Good;
import com.wms.mapper.GoodMapper;
import com.wms.service.GoodService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class GoodServiceImpl implements GoodService {
    private final GoodMapper goodMapper;

    @Override
    public List<Good> show() {
        List<Good> info = goodMapper.getInfo();
        if (CollectionUtils.isEmpty(info)) {
            return null;
        }
        List<Good> parent = info.stream().filter(item -> item.getParentId() == 0).toList();
        List<Good> children = info.stream().filter(item -> item.getParentId() > 0).toList();
        parent.forEach((c) -> {
            search(c, children);
        });
        return parent;
    }

    public static void search(Good current, List<Good> all) {
        List<Good> collect = all.stream().filter(a -> a.getParentId() == current.getId()).collect(Collectors.toList());
        List<Good> children = all.stream().filter(a -> Objects.equals(a.getParentId(), current.getId())).toList();
        children.forEach(c -> {
            if (c.equals(null)) {
                return;
            }
            search(c, all);
        });
        current.setChildren(children);
    }
}
